﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shape.Events;
using Shape.Mvp.Commands;
using System.Diagnostics.Contracts;
using Shape.Mvp.Views;
using System.Windows.Forms;

namespace Shape.Mvp
{
   public class DefaultApplicationController : IApplicationController
   {
#region Fields
      private IEventAggregator _eventAggregator;
      private ICommandFactory _commandFactory;

      private WindowManager _windowManager = new WindowManager();
#endregion

#region Constructor
      public DefaultApplicationController(IEventAggregator eventAggregator,
                                          ICommandFactory commandHandlerFactory)
      {
         Contract.Requires(eventAggregator != null);
         Contract.Requires(commandHandlerFactory != null);

         _eventAggregator = eventAggregator;
         _commandFactory = commandHandlerFactory;
      }
#endregion

#region Public Methods
      public void Execute<TCommand>() where TCommand : ICommand
      {
         var commandHandler = _commandFactory.CreateCommand<TCommand>();

         if (commandHandler != null)
         {
            commandHandler.Execute();
         }
      }

      public void Execute<TCommand, TArg>(TArg arg) where TCommand : ICommand<TArg>
      {
         var command = _commandFactory.CreateCommand<TCommand, TArg>();

         if (command != null)
         {
            command.Execute(arg);
         }
      }

      public void Publish<TEvent>(TEvent item)
      {
         _eventAggregator.Publish<TEvent>(item);
      }

      public void AddEventSubscriber(ISubscriber subscriber)
      {
         _eventAggregator.Subscribe(subscriber);
      }

      public IWindowMode Show(IView view)
      {
         return _windowManager.Show(view);
      }

      public IWindowMode Show(Form form)
      {
         return _windowManager.Show(form);
      }
#endregion
   }
}
